package servlet.home;

import data.Select;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "Login",value = "/home/login")
public class Login extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String user=request.getParameter("id");
            String pwd=request.getParameter("pwd");

            HttpSession session=request.getSession();
            if(user.equals("ROOT")){
                String count=Select.rootPwd(pwd);
                if(!count.equals(1+"")){
                    response.sendRedirect("/html/login.html?code=0");
                    return;
                }

                addCookie(session,"ROOT",user,response);
                response.sendRedirect("/html/root/manage.html");
            }else {
                int id=Integer.parseInt(user);
                Map<String,Object> map= Select.profileDetail(id);

                //如果密码不正确，返回错误信息
                if(!map.get("pwd").equals(pwd)){
                    response.sendRedirect("/html/login.html?code=0");
                    return;
                }

                //如果密码正确，对session进行写入。并且把session和id写入到cookie
                addCookie(session,"ID",user,response);
                response.sendRedirect("/html/admin/personage.html?id="+user);
            }
        }catch (Exception ex){
            response.sendRedirect("/html/login.html?code=0");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    private void addCookie(HttpSession session,String name,String user,HttpServletResponse response){
        session.setAttribute(user,session.getId());
        session.setMaxInactiveInterval(60*60);

        Cookie cookieId=new Cookie(name,user);
        Cookie cookieSId=new Cookie("SID",session.getId());

        cookieId.setPath("/");
        cookieSId.setPath("/");

        cookieId.setMaxAge(60*60);
        cookieSId.setMaxAge(60*60);
        response.addCookie(cookieId);
        response.addCookie(cookieSId);
    }
}
